package luke4fun.wheresmymoney.adapter;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.List;

import luke4fun.wheresmymoney.R;
import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.DBConstants;

public class ColorChooserAdapter extends ArrayAdapter<Integer> {
	
	private List<Integer> mColors;
	private Activity activity;
	private Spinner colorChooser;
	private AccDBHelper dbHelper;
	
	private boolean isInitial;
	
	public ColorChooserAdapter(Activity context, Spinner spinner, List<Integer> colors, boolean isInit) {
		super(context, R.layout.color_chooser, colors);
		this.activity = context;
		this.mColors = colors;
		this.colorChooser = spinner;
		this.isInitial = isInit;
		
		colorChooser.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedView, int position, long id) {
				RelativeLayout parent = (RelativeLayout) parentView.getParent();
				parent.setBackgroundColor(mColors.get(position));
				if (!isInitial) {
					LinearLayout lLayout = (LinearLayout) parent.getParent();
					TextView categoryId = (TextView) lLayout.findViewById(R.id.category_id);
					if (categoryId != null) {
						dbHelper = new AccDBHelper(activity);
						SQLiteDatabase db = dbHelper.getWritableDatabase();
						ContentValues cv = new ContentValues();
						cv.put(DBConstants.CATEGORY_COLOR, mColors.get(position));
						db.update(DBConstants.TABLE_CATEGORY, cv, DBConstants.CATEGORY_ID + "=?", new String[] {categoryId.getText().toString()});
						db.close();
						dbHelper.close();
					}
				}
				isInitial = false;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
			}
		});
	}

	@Override
	public Integer getItem(int position) {
	    return mColors.get(position);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
	    if (convertView == null) {
	        LayoutInflater inflater = activity.getLayoutInflater();
	        v = inflater.inflate(R.layout.color_chooser, null);
	    }
	    View colorView = v.findViewById(R.id.color);
	    colorView.setBackgroundColor(mColors.get(position));
	    TextView colorText = (TextView) v.findViewById(R.id.color_value);
	    colorText.setText(mColors.get(position) + "");
	    
	    return v;
	}
	
	@Override
	public View getDropDownView(int position, View convertView, ViewGroup parent) {
	    View v = (View) getView(position, convertView, parent);
	    return v;
	}
}
